<template>
  <a-modal
    :open="props.visible"
    title="AI 图片风格重绘"
    width="1000px"
    centered
    @cancel="handleCancel"
    :maskClosable="false"
    :keyboard="false"
  >
    <!-- 风格选择区域 -->
    <div class="redraw-content">
      <a-card class="style-selector-card" size="small">
        <template #title>
          <div class="card-title">
            <span class="title-icon">🎨</span>
            选择重绘风格
          </div>
        </template>
        <a-select
          v-model:value="selectedStyle"
          placeholder="请选择一个重绘风格"
          size="large"
          style="width: 100%"
          :disabled="isRedrawing"
        >
          <a-select-option
            v-for="style in redrawStyles || []"
            :key="style.value"
            :value="style.value"
          >
            <div class="style-option">
              <span class="style-name">{{ style.label }}</span>
              <a-tag size="small" color="blue">风格{{ style.value }}</a-tag>
            </div>
          </a-select-option>
        </a-select>
      </a-card>

      <!-- 图片对比区域 -->
      <div class="image-comparison">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-card class="image-card" size="small">
              <template #title>
                <div class="card-title">
                  <span class="title-icon">📷</span>
                  原图
                </div>
              </template>
              <div class="image-container">
                <a-image
                  :src="props.pictureData?.url"
                  fallback="placeholder.svg"
                  :preview="true"
                  class="display-image"
                />
                <div class="image-info">
                  <a-typography-text type="secondary" class="image-name">
                    {{ props.pictureData?.name || '未命名图片' }}
                  </a-typography-text>
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card class="image-card" size="small">
              <template #title>
                <div class="card-title">
                  <span class="title-icon">✨</span>
                  重绘结果
                  <a-tag v-if="currentStyleLabel" color="processing" size="small" class="style-tag">
                    {{ currentStyleLabel }}
                  </a-tag>
                </div>
              </template>
              <div class="image-container">
                <template v-if="!isRedrawing && !redrawResultUrl">
                  <a-empty class="empty-result" description="选择风格后开始重绘">
                    <template #image>
                      <div class="empty-icon">🖼️</div>
                    </template>
                  </a-empty>
                </template>
                <template v-else-if="isRedrawing">
                  <div class="loading-container">
                    <a-spin size="large" />
                    <div class="loading-text">
                      <a-typography-title :level="4" class="loading-title">
                        AI 正在重绘中...
                      </a-typography-title>
                      <a-typography-text type="secondary">
                        这可能需要几分钟时间，请耐心等候
                      </a-typography-text>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <a-image
                    :src="redrawResultUrl"
                    fallback="placeholder.svg"
                    :preview="true"
                    class="display-image"
                  />
                  <div class="result-actions">
                    <a-button
                      type="primary"
                      size="large"
                      @click="saveRedrawResult"
                      :loading="isSaving"
                      class="save-button"
                    >
                      <template #icon>
                        <span>💾</span>
                      </template>
                      保存到图库
                    </a-button>
                  </div>
                </template>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>

    <template #footer>
      <div class="modal-footer">
        <a-button size="large" @click="handleCancel" :disabled="isRedrawing"> 取消 </a-button>
        <a-button
          type="primary"
          size="large"
          :disabled="isRedrawing || !selectedStyle"
          :loading="isRedrawing"
          @click="startRedrawing"
        >
          <template #icon>
            <span>🎨</span>
          </template>
          {{ isRedrawing ? '重绘中...' : '开始重绘' }}
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onUnmounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import {
  getPictureStyleRegenResult,
  getPictureStyleRegenTaskId,
  uploadPictureByUrl,
} from '@/api/picture'
import type { PictureStyleRegenRequest, PictureUploadRequest } from '@/types/picture'
import type { Picture } from '@/types/picture'

// 定义组件接收的 props
const props = defineProps<{
  visible: boolean
  pictureData: Picture | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void // 新增刷新事件
}>()

const router = useRouter()

const handleCancel = () => {
  emit('update:visible', false)
  // 触发父组件刷新，以便看到新保存的图片
  emit('refresh')
}

// --- 状态管理 ---
const selectedStyle = ref<string>('')
const isRedrawing = ref(false)
const redrawResultUrl = ref<string>('')
const pollInterval = ref<number | null>(null)
const taskId = ref<string>('')
const isSaving = ref(false)

interface StyleOption {
  label: string
  value: string
}

const redrawStyles = ref<StyleOption[]>([
  { label: '复古漫画', value: '0' },
  { label: '3D童话', value: '1' },
  { label: '二次元', value: '2' },
  { label: '小清新', value: '3' },
  { label: '未来科技', value: '4' },
  { label: '国画古风', value: '5' },
  { label: '将军百战', value: '6' },
  { label: '炫彩卡通', value: '7' },
  { label: '清雅国风', value: '8' },
  { label: '普迎新年', value: '9' },
  { label: '国风工笔', value: '14' },
  { label: '恭贺新禧', value: '15' },
  { label: '童话世界', value: '30' },
  { label: '黏土世界', value: '31' },
  { label: '像素世界', value: '32' },
  { label: '冒险世界', value: '33' },
  { label: '日漫世界', value: '34' },
  { label: '3D世界', value: '35' },
  { label: '二次元世界', value: '36' },
  { label: '手绘世界', value: '37' },
  { label: '蜡笔世界', value: '38' },
  { label: '冰糖贴世界', value: '39' },
  { label: '吧唧世界', value: '40' },
])

// 计算当前选中风格的标签
const currentStyleLabel = computed(() => {
  if (!selectedStyle.value || !redrawStyles.value) return ''
  return redrawStyles.value.find((s) => s.value === selectedStyle.value)?.label || ''
})

const startRedrawing = async () => {
  if (!selectedStyle.value) {
    message.warning('请先选择一个重绘风格')
    return
  }
  if (!props.pictureData || !props.pictureData.url || !props.pictureData.spaceId) {
    message.error('图片信息不完整，无法重绘')
    return
  }
  isRedrawing.value = true
  redrawResultUrl.value = ''

  const request: PictureStyleRegenRequest = {
    id: props.pictureData.spaceId || '0',
    imageUrl: props.pictureData.url,
    styleIndex: parseInt(selectedStyle.value),
  }

  try {
    const response = await getPictureStyleRegenTaskId(request)
    console.log('重绘请求响应:', response)
    // console.log('响应数据结构:', response.data)

    // 正确的访问路径：response.data.data.output.taskId（根据实际调试输出）
    const responseData = response as { data: { data: { output: { taskId: string } } } }
    const taskOutput = responseData?.data?.data?.output
    if (taskOutput?.taskId) {
      taskId.value = taskOutput.taskId
      console.log('获取到 Task ID:', taskId.value)
      // 启动轮询
      startPolling(taskId.value)
    } else {
      console.error('无法获取taskId，响应结构:', responseData)
      message.error('获取任务ID失败')
      isRedrawing.value = false
    }
  } catch (error) {
    message.error('重绘请求失败')
    console.error('重绘请求错误:', error)
    isRedrawing.value = false
  }
}

// 启动轮询请求
const startPolling = (taskId: string) => {
  console.log('开始轮询，任务ID:', taskId)
  pollInterval.value = window.setInterval(async () => {
    try {
      const result = await getPictureStyleRegenResult(taskId)
      console.log('轮询响应:', result)
      // console.log('轮询响应数据:', result.data)

      // 正确的访问路径：result.data.data.output（根据实际调试输出）
      const resultData = result as {
        data: {
          data: {
            output: { taskStatus: string; results?: { url: string }[]; errorMessage?: string }
          }
        }
      }
      const taskOutput = resultData?.data?.data?.output
      const taskStatus = taskOutput?.taskStatus
      console.log('任务状态:', taskStatus)

      if (taskStatus === 'SUCCEEDED') {
        // 处理成功逻辑
        console.log('任务成功完成，完整output结构:', taskOutput)

        // 正确的字段名是 results（复数），不是 result（单数）
        const resultUrl = taskOutput?.results?.[0]?.url
        console.log('重绘结果URL:', resultUrl)

        if (resultUrl) {
          redrawResultUrl.value = resultUrl
          stopPolling()
          message.success('图片重绘成功！')
        } else {
          console.error('无法获取重绘结果URL，响应结构:', resultData)
          message.error('重绘结果获取失败')
          stopPolling()
        }
      } else if (taskStatus === 'FAILED') {
        const errorMessage = taskOutput?.errorMessage || '重绘失败'
        console.error('重绘失败:', errorMessage)
        message.error(errorMessage)
        stopPolling()
      } else if (taskStatus === 'RUNNING' || taskStatus === 'PENDING') {
        // 任务运行中，继续轮询
        console.log('任务运行中，状态:', taskStatus)
      } else {
        console.log('未知任务状态:', taskStatus, '完整响应:', resultData)
      }
    } catch (error) {
      console.error('轮询请求失败:', error)
      message.error('查询任务状态失败')
      stopPolling()
    }
  }, 3000) // 每隔 3 秒轮询一次
}

// 停止轮询
const stopPolling = () => {
  if (pollInterval.value !== null) {
    clearInterval(pollInterval.value)
    pollInterval.value = null
    isRedrawing.value = false
  }
}

// 保存重绘结果到图库
const saveRedrawResult = async () => {
  if (!redrawResultUrl.value || !props.pictureData?.spaceId) {
    message.error('保存失败：缺少必要信息')
    return
  }

  isSaving.value = true

  try {
    // 生成一个随机的图片名称，避免名称过长
    const randomSuffix = Math.random().toString(36).substring(2, 8)
    const pictureName = `重绘_${selectedStyle.value}_${randomSuffix}`

    const uploadRequest: PictureUploadRequest = {
      fileUrl: redrawResultUrl.value, // 重绘结果的URL
      picName: pictureName,
      spaceId: props.pictureData.spaceId,
    }

    // 使用新的URL上传接口
    const response = await uploadPictureByUrl(uploadRequest)

    if (response.data) {
      message.success('保存成功！即将返回图片列表')

      // 关闭弹窗
      emit('update:visible', false)

      // 跳转回空间图片页面
      setTimeout(() => {
        console.log('跳转到空间页面，图片ID:', response.data.id)
        router.push({
          path: `/spaces/${props.pictureData?.spaceId}/pictures`,
        })
      }, 1500) // 增加到1.5秒，让用户看到成功消息
    }
  } catch (error) {
    console.error('保存重绘结果失败:', error)
    message.error('保存失败，请重试')
  } finally {
    isSaving.value = false
  }
}

// 组件卸载时，确保清除定时器，避免内存泄漏
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.redraw-content {
  padding: 0;
}

.style-selector-card {
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2937;
}

.title-icon {
  font-size: 18px;
}

.style-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.style-name {
  font-weight: 500;
}

.image-comparison {
  margin-bottom: 16px;
}

.image-card {
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.image-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.image-container {
  position: relative;
  min-height: 320px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 6px;
  overflow: hidden;
}

.display-image {
  max-width: 100%;
  max-height: 280px;
  object-fit: contain;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.image-info {
  position: absolute;
  bottom: 12px;
  left: 12px;
  right: 12px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(8px);
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.image-name {
  font-size: 13px;
  font-weight: 500;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.style-tag {
  margin-left: 8px;
}

.empty-result {
  padding: 60px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  gap: 24px;
}

.loading-text {
  text-align: center;
}

.loading-title {
  margin-bottom: 8px !important;
  color: #1f2937;
}

.result-actions {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

.save-button {
  border-radius: 8px;
  height: 44px;
  padding: 0 24px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
}

.save-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(24, 144, 255, 0.4);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-comparison :deep(.ant-row) {
    flex-direction: column;
  }

  .image-comparison :deep(.ant-col) {
    margin-bottom: 16px;
  }

  .image-container {
    min-height: 240px;
  }

  .display-image {
    max-height: 200px;
  }
}

/* Ant Design Vue 组件样式覆盖 */
:deep(.ant-modal-header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 20px 24px 16px;
}

:deep(.ant-modal-title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-modal-footer) {
  padding: 16px 24px 24px;
  border-top: none;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  min-height: 48px;
}

:deep(.ant-card-head-title) {
  padding: 12px 0;
  font-size: 14px;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-select-large) {
  font-size: 16px;
}

:deep(.ant-select-selector) {
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

:deep(.ant-select-focused .ant-select-selector) {
  border-color: #1890ff;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

:deep(.ant-empty-description) {
  color: #9ca3af;
  font-size: 14px;
}
</style>
